package logic

import (
	"baidu-dev/cache"
	"baidu-dev/models"
	"context"
	"errors"

	"baidu-dev/baidurpc/baidurpc"
	"baidu-dev/baidurpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ForgetPasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewForgetPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ForgetPasswordLogic {
	return &ForgetPasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 修改密码
func (l *ForgetPasswordLogic) ForgetPassword(in *baidurpc.ForgetPasswordRequest) (*baidurpc.ForgetPasswordResponse, error) {
	// todo: add your logic here and delete this line

	var user models.User

	if err := user.FindByUserMobile(models.DB, in.Mobile); err != nil {
		return nil, errors.New("当前手机号未注册,请前往注册")
	}

	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Result()
	if result != in.SmsCode {
		return nil, errors.New("验证码输入错误,请重新输入")
	}

	if in.Password != in.NewPassword {
		return nil, errors.New("两次密码不一致,请重新输入")
	}

	if in.NewPassword == user.Password {
		return nil, errors.New("新密码与旧密码一致,请重新输入")
	}

	in.NewPassword = user.Password

	if err := user.PasswordUpdates(models.DB); err != nil {
		return nil, errors.New("修改失败,请联系管理员")
	}

	return &baidurpc.ForgetPasswordResponse{
		UserId: int64(user.ID),
	}, nil
}
